package com.csl.jmu.demo.common;

import com.csl.jmu.demo.entity.UserInfo;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * <pre>
 * 描述：加密
 * </pre>
 *
 * @类名：com.csl.jmu.demo.common.PasswordHelper
 * @作者： 1410HL0236
 * @创建日期: 2019/11/19 08:47
 */
public class PasswordHelper {
  private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
  public static final String ALGORITHM_NAME = "md5"; // 基础散列算法
  public static final int HASH_ITERATIONS = 2; // 自定义散列次数

  public void encryptPassword(UserInfo user) {
    // 随机字符串作为salt因子，实际参与运算的salt我们还引入其它干扰因子
    user.setSalt(randomNumberGenerator.nextBytes().toHex());
    String newPassword = new SimpleHash(ALGORITHM_NAME, user.getPassword(),
            ByteSource.Util.bytes(user.getCredentialsSalt()), HASH_ITERATIONS).toHex();
    user.setPassword(newPassword);
  }
}
